package com.zzg.test2.manager;


import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName: DiskCacheManager
 * @Description:
 * @Author: zhouzhiguo
 * @Date: 2025/8/26 18:31
 * @Version: 5.3.8
 */
public class DiskCacheManager {
    private static final String TAG = "DiskCacheManager";
    private Context context;
    private static final String CACHE_DIR = "webview_cache";

    public DiskCacheManager(Context context) {
        this.context = context;
    }

    public InputStream getFromDiskCache(String url) {
        try {
            String filename = getCacheFileName(url);
            File cacheFile = new File(context.getCacheDir() + File.separator + CACHE_DIR, filename);

            if (cacheFile.exists()) {
                return new FileInputStream(cacheFile);
            }
        } catch (IOException e) {
            Log.e(TAG, "Error reading from disk cache", e);
        }
        return null;
    }

    public void saveToDiskCache(String url, InputStream inputStream) {
        try {
            String filename = getCacheFileName(url);
            File cacheDir = new File(context.getCacheDir(), CACHE_DIR);
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }

            File cacheFile = new File(cacheDir, filename);
            FileOutputStream outputStream = new FileOutputStream(cacheFile);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            Log.e(TAG, "Error writing to disk cache", e);
        }
    }

    private String getCacheFileName(String url) {
        return String.valueOf(url.hashCode());
    }

    public void clearDiskCache() {
        File cacheDir = new File(context.getCacheDir(), CACHE_DIR);
        if (cacheDir.exists() && cacheDir.isDirectory()) {
            File[] files = cacheDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    file.delete();
                }
            }
        }
    }
}